package com.sinux.sshUser.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinux.sshUser.entity.User;
import com.sinux.sshUser.service.UserServiceI;
import com.sinux.sshUser.util.MUtil;




/**
 * @author WangGan
 * @version 2017年5月23日 下午11:00:29 
 * 
 */

@Controller
public class UserController {
	
	@Autowired
	private UserServiceI userService;
	/***登录注册模块 start***/
	@RequestMapping("/sys")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model){
		User user = (User) request.getSession().getAttribute("sshUser");// user为空
		// 判断是否为空
		if (user == null) {
			return "modules/logReg";
			//return "modules/index";//测试
		} else {
			model.addAttribute("user",user);
			return "modules/index";
		}
	}
	
	//管理登录
	@RequestMapping("/login")
	public String login() {
		// 如果已登录，再次访问主页，则退出原账号。
		// 如果已经登录，则跳转到管理首页
		return "modules/logReg";
	}
	
	/**
	 * 验证登录
	 * @param request
	 * @param response
	 * @param user
	 * @return map
	 */
	@ResponseBody
	@RequestMapping("/checklog")												
	public Map<String, Object> checkLogin(HttpServletRequest request, HttpServletResponse response, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(user!=null){
			//对密码加密
			user.setPwd(MUtil.encryptByMd5(user.getPwd()));
			//创建用户名和密码的令牌  
			String logname=user.getLogname();
			String pwd=user.getPwd();
			UsernamePasswordToken token = new UsernamePasswordToken(logname,pwd);
			//记录该令牌  
			token.setRememberMe(true); 
			//subject理解成权限对象。类似user  
			Subject subject = SecurityUtils.getSubject(); 
			try {  
				subject.login(token);
				User _user = userService.login(user);
				request.getSession().setAttribute("sshUser", _user);
				map.put("success", true);
				map.put("msg", "登录成功！");
			} catch (UnknownAccountException ex) {
				//用户名没有找到。  
				ex.printStackTrace();
				map.put("success", false);
				map.put("msg", "用户名没有找到");
			} catch (IncorrectCredentialsException ex) {
				//用户名密码不匹配。  
				//ex.printStackTrace();
				map.put("success", false);
				map.put("msg", "用户名密码不匹配");
			}catch (AuthenticationException e) {
				//其他的登录错误  
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "登录异常!");
			}  
			//验证是否成功登录的方法  
//			if (subject.isAuthenticated()) {  
//				
//			}  
			return map;
			
//			System.out.println(user.getLogname()+"*****"+user.getPwd());
//			user.setPwd(MUtil.encryptByMd5(user.getPwd()));//MD5加密
//			User _user = userService.login(user);
//			//User _user=null;
//			if (_user == null) {
//				map.put("success", false);
//				map.put("msg", "登录失败！");
//			} else {
//				request.getSession().setAttribute("sshUser", _user);
//				map.put("success", true);
//				map.put("msg", "登录成功！");
//			}
//			return map;
		}else{
			map.put("success", false);
			map.put("msg", "登录异常,未获取信息!");
			return map;
		}
		
	}
	//注册
	@ResponseBody
	@RequestMapping("/reguser")
	public Map<String, Object> regUser(HttpServletRequest request,HttpServletResponse response,User user){
		Map<String, Object> map =new HashMap<String, Object>();
		System.out.println("user ID:"+user.getUid());
		if (user == null) {
			map.put("success", false);
			map.put("msg", "注册失败！");
		} else {
			try {
				user.setUstate(MUtil.STATE_YES);//设置默认状态为启用
				user.setPwd(MUtil.encryptByMd5(user.getPwd()));//MD5加密
				userService.reg(user);
				request.getSession().setAttribute("sshUser", user);
			} catch (Exception e) {
				System.out.println("注册出错");
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "注册失败！");
				return map;
			}
			map.put("success", true);
			map.put("msg", "注册成功！");
			}
			return map;
	}
	/***登录注册模块 end***/
	
	@ResponseBody
	@RequestMapping("/user/list")
	public List<User> index(Model model) {
		model.addAttribute("userList", userService.findAllUserList());
		List<User> list=userService.findAllUserList();
		return list;
	}
	
	/***分页用户列表***/
	@ResponseBody
	@RequestMapping("/usertab")
	public Map<String, Object> userindex(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String ,Object> map=new HashMap<String ,Object>();
		int pageIndex =Integer.valueOf(request.getParameter("page")); //第几页的数据  
	    int pageSize = Integer.valueOf(request.getParameter("rows")); //每页多少条数据  
	    List<User> users=userService.findUserPageing(pageIndex,pageSize);
		//model.addAttribute("userList", userService.findAllUserList()); 
	    int total=userService.findAllUserList().size();
//	    Paging page=new Paging();
//	    page.setTotal(total);
//	    page.setUsers(users);
	    map.put("total", total);
	    map.put("rows", users);
		return map;
	}

	//删除用户数据(改变状态,并非删除)
	@RequestMapping("/closeuser")
	public Object dfasf(HttpServletRequest request, HttpServletResponse response, Model model){
		String uid=request.getParameter("uid");
		System.out.println("UID:"+uid);
		userService.upState(uid,0);//删除状态
		return null;
			
	}
	
	//恢复用户数据(改变状态,并非删除)
	@RequestMapping("/restoreuser")
	public Object sgeh(HttpServletRequest request, HttpServletResponse response, Model model){
		String uid=request.getParameter("uid");
		System.out.println("UID:"+uid);
		userService.upState(uid,1);//恢复状态
		return null;
				
		}
	//模糊搜索 分页
	@ResponseBody
	@RequestMapping("/seachusertab")
	public Map<String ,Object> seachuserindex(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String ,Object> map=new HashMap<String ,Object>();
		int pageIndex =Integer.valueOf(request.getParameter("page")); //第几页的数据  
	    int pageSize = Integer.valueOf(request.getParameter("rows")); //每页多少条数据  
		String value=request.getParameter("txt");
		List<User> users=userService.findUserList(value, pageIndex, pageSize);
		//model.addAttribute("userList", userService.findUserList(txt));
		int total=userService.findUserList(value).size();
		map.put("total", total);
	    map.put("rows", users);
		return map;
	}
	
	

}
